package com.ruoyi.system.mobile.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.ruoyi.common.enums.UserStatus;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.system.mobile.bo.TAppUserAddBo;
import com.ruoyi.system.mobile.bo.TAppUserEditBo;
import com.ruoyi.system.mobile.bo.TAppUserQueryBo;
import com.ruoyi.system.mobile.domain.AppUser;
import com.ruoyi.system.mobile.mapper.AppUserMapper;
import com.ruoyi.system.mobile.service.AppUserService;
import com.ruoyi.system.mobile.vo.TAppUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * APP用户Service业务层处理
 *
 * @author ruoyi
 * @date 2021-05-21
 */
@Service
public class AppUserServiceImpl extends ServiceImpl<AppUserMapper, AppUser> implements AppUserService {
    private static final Logger log = LoggerFactory.getLogger(AppUserServiceImpl.class);

    @Autowired
    private AppUserService itAppUserService;

    @Autowired
    private AppUserMapper tAppUserMapper;

    @Override
    public TAppUserVo queryById(Long id) {
        AppUser db = this.baseMapper.selectById(id);
        return BeanUtil.toBean(db, TAppUserVo.class);
    }

    @Override
    public List<TAppUserVo> queryList(TAppUserQueryBo bo) {
        LambdaQueryWrapper<AppUser> lqw = Wrappers.lambdaQuery();
        lqw.like(StrUtil.isNotBlank(bo.getLoginName()), AppUser::getLoginName, bo.getLoginName());
        lqw.like(StrUtil.isNotBlank(bo.getName()), AppUser::getName, bo.getName());
        lqw.eq(StrUtil.isNotBlank(bo.getSex()), AppUser::getSex, bo.getSex());
        lqw.eq(StrUtil.isNotBlank(bo.getUserType()), AppUser::getUserType, bo.getUserType());
        return entity2Vo(this.list(lqw));
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<TAppUserVo> entity2Vo(Collection<AppUser> collection) {
        List<TAppUserVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, TAppUserVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<AppUser> page = (Page<AppUser>) collection;
            Page<TAppUserVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public Boolean insertByAddBo(TAppUserAddBo bo) {
        AppUser add = BeanUtil.toBean(bo, AppUser.class);
        validEntityBeforeSave(add);
        return this.save(add);
    }

    @Override
    public Boolean updateByEditBo(TAppUserEditBo bo) {
        AppUser update = BeanUtil.toBean(bo, AppUser.class);
        validEntityBeforeSave(update);
        return this.updateById(update);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(AppUser entity) {
        //TODO 做一些数据校验,如唯一约束
        AppUser appUser = tAppUserMapper.selectUserByUserName(entity.getLoginName());
        if(appUser!=null){
            throw new BaseException("对不起，您的登录名"+appUser.getLoginName()+"已经被注册");
        }
    }



    @Override
    public AppUser login(String loginName, String password) {
        AppUser user = tAppUserMapper.selectUserByUserName(loginName);
        if (Validator.isNull(user)) {
            log.info("登录用户：{} 不存在.", loginName);
            throw new UsernameNotFoundException("登录用户：" + loginName + " 不存在");
        } else if (UserStatus.DELETED.getCode().equals(user.getDelFlag())) {
            log.info("登录用户：{} 已被删除.", loginName);
            throw new BaseException("对不起，您的账号：" + loginName + " 已被删除");
        }
        if(!password.equals(user.getLoginPwd())){
            log.info("密码错误");
            throw new BaseException("密码错误");
        }
        return user;
    }


}
